#include "naturalsortcomparator.h"
#include <QDebug>
#include <QFileInfo>
#include <algorithm>

bool NaturalSortComparator::naturalCompare(const QString& a, const QString& b)
{
    if (a == b) return false;

    // 获取文件名（去除路径）
    QString nameA = QFileInfo(a).baseName();
    QString nameB = QFileInfo(b).baseName();

    // 分解为标记
    QList<SortToken> tokensA = tokenize(nameA);
    QList<SortToken> tokensB = tokenize(nameB);

    // 逐个比较标记
    int minSize = qMin(tokensA.size(), tokensB.size());
    for (int i = 0; i < minSize; ++i) {
        int result = compareTokens(tokensA[i], tokensB[i]);
        if (result != 0) {
            return result < 0;
        }
    }

    // 如果前面所有标记都相等，短的排在前面
    return tokensA.size() < tokensB.size();
}

QList<int> NaturalSortComparator::sortIndices(const QStringList& filenames, const QList<int>& indices)
{
    QList<int> sortedIndices = indices;

    for (int i = 0; i < indices.size(); ++i) {
        int index = indices[i];
        if (index >= 0 && index < filenames.size()) {
        }
    }

    // 使用自然排序算法排序索引
    std::sort(sortedIndices.begin(), sortedIndices.end(),
              [&filenames](int a, int b) {
                  if (a >= 0 && a < filenames.size() && b >= 0 && b < filenames.size()) {
                      bool result = naturalCompare(filenames[a], filenames[b]);
                      return result;
                  }
                  return a < b;
              });

    for (int i = 0; i < sortedIndices.size(); ++i) {
        int index = sortedIndices[i];
        if (index >= 0 && index < filenames.size()) {
        }
    }

    return sortedIndices;
}

QList<int> NaturalSortComparator::reverseIndices(const QList<int>& indices)
{
    QList<int> reversedIndices = indices;
    std::reverse(reversedIndices.begin(), reversedIndices.end());
    return reversedIndices;
}

QList<NaturalSortComparator::SortToken> NaturalSortComparator::tokenize(const QString& filename)
{
    QList<SortToken> tokens;
    if (filename.isEmpty()) return tokens;


    // 简化策略：提取所有数字，按数字值排序
    QRegularExpression numberRegex(R"(\d+)");
    QRegularExpressionMatchIterator iterator = numberRegex.globalMatch(filename);

    // 提取第一个数字作为排序依据
    if (iterator.hasNext()) {
        QRegularExpressionMatch match = iterator.next();
        QString numberPart = match.captured(0);

        qint64 number = numberPart.toLongLong();
        int leadingZeros = 0;

        // 计算前导零
        if (numberPart.startsWith('0') && numberPart.length() > 1) {
            for (int i = 0; i < numberPart.length(); ++i) {
                if (numberPart[i] == '0') {
                    leadingZeros++;
                } else {
                    break;
                }
            }
        }

        tokens.append(SortToken(SortToken::Number, numberPart, number, leadingZeros));
    } else {
        // 没有数字，添加整个文件名作为文本
        tokens.append(SortToken(SortToken::Text, filename));
    }

    return tokens;
}

int NaturalSortComparator::compareTokens(const SortToken& a, const SortToken& b)
{
    // 简化比较：主要按数字值排序
    if (a.type == SortToken::Number && b.type == SortToken::Number) {
        // 数字比较：直接按数值大小
        if (a.number != b.number) {
            return (a.number < b.number) ? -1 : 1;
        }
        // 数值相等时，前导零少的排在前面（"1" 排在 "01" 前面）
        if (a.leadingZeros != b.leadingZeros) {
            return (a.leadingZeros < b.leadingZeros) ? -1 : 1;
        }
        return 0;
    } else if (a.type == SortToken::Text && b.type == SortToken::Text) {
        // 文本比较：按字典序
        int result = a.text.compare(b.text, Qt::CaseInsensitive);
        return (result < 0) ? -1 : (result > 0) ? 1 : 0;
    } else {
        // 类型不同时，数字排在文本前面
        return (a.type == SortToken::Number) ? -1 : 1;
    }
}

void NaturalSortComparator::extractNumberInfo(const QString& numberText, qint64& number, int& leadingZeros)
{
    number = numberText.toLongLong();
    leadingZeros = 0;

    // 计算前导零个数
    if (numberText.startsWith('0') && numberText.length() > 1) {
        for (int i = 0; i < numberText.length(); ++i) {
            if (numberText[i] == '0') {
                leadingZeros++;
            } else {
                break;
            }
        }
    }
}